<template>
    <div class="page-container">
        <el-form :inline="true" :model="search" size="small" ref="searchForm">
            <el-form-item label="标题:">
                <el-input placeholder="请输入名称" v-model="search.title" @change="filterSubmit" clearable></el-input>
            </el-form-item>
            <el-form-item label="状态:">
                <el-select v-model="search.status" placeholder="请选择状态" @change="filterSubmit" clearable>
                    <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="filterSubmit">查询</el-button>
                <el-button @click="reset()">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row>
            <!-- <el-button size="small" type="primary" @click="add" v-if="classData.numRestrict == 0 || list.length < 1">添加</el-button> -->
            <el-button size="small" type="primary" @click="add" >添加</el-button>
        </el-row>
        <div class="table-list">
            <el-table :data="list" size="small">
                <!-- <el-table-column label="ID" prop="id"></el-table-column> -->
                <el-table-column label="文章/视频标题" prop="title"></el-table-column>
				<el-table-column label="类型" prop="title">
					<template #default="scope">
							<el-tag size="small" class="ml-2" type="success" v-if="scope.row.articleType == '0'">文章</el-tag>
							  <el-tag size="small" class="ml-2" type="warning" v-else>视频</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="作者" prop="author">
				</el-table-column>
				<el-table-column label="标签" width="400">
					<template #default="scope">
						<template v-for=" item in scope.row.articleTags">
							<el-tag size="small" class="ml-2" style="margin-right: 5px;" type="success" >{{item.tagName}}</el-tag>
						</template>
					</template>
				</el-table-column>
                <el-table-column label="状态" prop="status">
                    <template #default="scope">
                        <el-switch size="small" v-model="scope.row.status" :active-value="1" :inactive-value="2"
                            :active-text="scope.row.status == 1 ? '已发布' : '未发布'" @change="changeStatus(scope.row)"></el-switch>
                    </template>
                </el-table-column>
               <!-- <el-table-column label="摘要" prop="articleAbstract"></el-table-column> -->
                <el-table-column label="发布时间" prop="createTime"></el-table-column>
                <el-table-column label="操作" align="center" fixed="right" width="120">
                    <template #default="scope">
                        <!-- <el-button type="primary" link size="small" @click="relationQuestion(scope.row)">试卷详情</el-button> -->
                        <el-button type="primary" link size="small" @click="editRow(scope.row)">修改</el-button>
                        <el-button type="primary" link size="small" v-if="classData.numRestrict == 0"
                            @click="delRow(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="page-block">
            <el-pagination v-model:currentPage="current" v-model:page-size="page" :page-sizes="[10, 20, 30, 40]"
                :small="true" :disabled="false" :background="false" layout="total, sizes, prev, pager, next, jumper"
                :total="total" :hide-on-single-page="true" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>

        <detail-form v-model:dialogDrawer="dialogFormVisible" :defaultForm="form"  @onDetailSubmit="onDetailSubmit"></detail-form>
    </div>
</template>
  
<script>
import { reactive, toRefs, watch, onMounted } from 'vue'
import DetailForm from './DetailForm.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { pageList, get, updateStatus, remove } from '/@/api/ws/article'
import { getArticleClass } from '/@/api/ws/articleClass'
import { useUserInfo } from '/@/stores/userInfo'
import { storeToRefs } from 'pinia';
export default {
    name: 'ArticleListDetail',
    components: {
        DetailForm
    },
    props: {
        activeName: {
            type: String,
            default: null
        }
    },
    setup(props) {
        const {
            activeName
        } = toRefs(props)
        const storeUserInfo = useUserInfo() 
        const { userInfos } = storeToRefs(storeUserInfo)
        watch(() => activeName.value,
            (newVal, oldVal) => {
                let classType = 'class_about'
                let flag = false
                if (newVal == 'first') {
                    flag = true
                } else if (newVal == 'second') {
                    classType = 'class_dynamic'
                    flag = true
                } else if (newVal == 'third') {
                    classType = 'class_case'
                    flag = true
                } else if (newVal == 'fourth') {
                    classType = 'class_cooperation'
                    flag = true
                } else if (newVal == 'fifth') {
                    flag = false
                }
                if (flag) {
                    state.classSearchForm.classType = classType
                    getList()
                    reset()
                }

            }
        )
        const state = reactive({
            list: [],
            search: {
                current: 1,
                size: 10
            },
            title: '新增',
            form: {},
            dialogFormVisible: false,
            total: 100,
            current: 1,
            page: 10,
            statusOptions: [
                {
                    value: '2',
                    label: '未发布',
                },
                {
                    value: '1',
                    label: '已发布',
                },
            ],
            dialogRelationQuestionVisible: false,
            classSearchForm: {
                isDefault: 0,
                classType: 'class_about'
            },
            classData: {
                numRestrict: 1
            }
        })
        const add = () => {
            restForm()
            state.title = '新增'
            state.dialogFormVisible = true
            console.log(state.form)
        }
        const editRow = row => {
            state.title = '编辑'
            get(row.id).then(res => {
                state.form = res.data
                state.form.articleType = parseInt(res.data.articleType)
				state.form.status = parseInt(res.data.status)
				let backageImage = []
				if(res.data.image){
				  let images = res.data.image.split(",")
				  for(let i of images){
					  backageImage.push({name:'',url:i})
				  }
				  
				}
				state.form.backageImage = backageImage
				
            })
            state.dialogFormVisible = true
        }
        const restForm = () => {
            state.form = {
                id: null,
                status: 0,
                title: null,
                articleAbstract: null,
                content:null,
                classId: state.classData.id,
                backageImage:[],
                image:null,
				articleSkuRelations:[],
				articleTags:[],
				articleType:0,
				author:userInfos.value.userName,
                createTime: getNowDate()
            }
        }
        const delRow = row => {
            ElMessageBox.confirm(
                '是否确认删除名称为"' + row.name + '"的数据项？',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                remove(row.id).then(res => {
                    if (res.code == 0) {
                        ElMessage({
                            type: 'success',
                            message: '删除成功',
                        })
                        getList()
                    } else {
                        ElMessage({
                            type: 'error',
                            message: '删除失败：' + res.message,
                        })
                    }
                })

            }).catch()
        }
        const getList = async () => {
            await getArticleClass(state.classSearchForm).then(res => {
                if (res.data) {
                    state.classData = res.data
                    state.search.classId = res.data.id
                }
            })
            await pageList(state.search).then(res => {
                if(res.data){
                    state.list = res.data.records
                    state.total = res.data.total
                }
            })
        }
        const handleSizeChange = e => {
            state.search.size = e
            getList()
        }
        const handleCurrentChange = e => {
            state.search.current = e
            state.current = e
            getList()
        }
        const onDetailSubmit = () => {
            getList()
            state.dialogFormVisible = false
        }
        const changeStatus = (row) => {
            updateStatus({ id: row.id, status: row.status }).then(res => {
                if (res.code == 0) {
                    ElMessage.success('修改成功')
                    getList()
                } else {
                    ElMessage.error('修改失败:' + res.message)
                }
            })
        }
        const filterSubmit = () => {
            state.search.current = 1
            getList()
        }
        const reset = () => {
            state.search = {
                current: 1,
                size: 10,
                status: null,
                title: null
            }
            getList()
        }

        const relationQuestion = (row) => {
            state.form = row
            state.dialogRelationQuestionVisible = true
        }
        const getNowDate = () => {
            var date = new Date();//时间戳为10位需*1000，时间戳为13位的话不需乘1000
            var Y = date.getFullYear() + '-';
            var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1):date.getMonth()+1) + '-';
            var D = (date.getDate()< 10 ? '0'+date.getDate():date.getDate())+ ' ';
            var h = (date.getHours() < 10 ? '0'+date.getHours():date.getHours())+ ':';
            var m = (date.getMinutes() < 10 ? '0'+date.getMinutes():date.getMinutes()) + ':';
            var s = date.getSeconds() < 10 ? '0'+date.getSeconds():date.getSeconds();
        return Y+M+D+h+m+s;
        }
        onMounted(() => {
            getList()
            // getArticleClassOne()
        })
        return {
            add,
            editRow,
            delRow,
            handleSizeChange,
            handleCurrentChange,
            onDetailSubmit,
            restForm,
            changeStatus,
            filterSubmit,
            reset,
            relationQuestion,
            getNowDate,
            // getArticleClassOne,
            ...toRefs(state)
        }
    }
}
</script>
  
<style lang="scss" scoped>
.page-container {
    .table-list {
        background: var(--next-color-white);
        margin-top: 10px;

        :deep(.el-table__header-wrapper .el-table__cell) {
            background: var(--el-color-primary-light-9);
            color: var(--next-bg-menuBar-light-1);
        }
    }
}
</style>